import sys
import subprocess
import os
import json


def run_cmd(command):
    try:
        result = subprocess.run(command, shell=True, capture_output=True, text=True)
        if result.returncode == 0:
            output = result.stdout.strip()
        else:
            output = result.stderr.strip()
    except Exception as e:
        output = str(e)
    return output

def cargo_test(func_name_list_filepath, project_path):
    # Read func name list from the filepath. Then, for the function in function name list, cargo test each test looply.
    with open(func_name_list_filepath, 'r') as f:
        func_name_list = f.read().split('\n')

    output_list = []

    for func_name in func_name_list:
        output = run_cmd(f'cd {project_path} && cargo test {func_name}')
        output_list.append((func_name, output))
        output_last_line = output.split('\n')[-1]
        if output_last_line.find('ok') != -1:
            print(f'{func_name} passed!')
        else:
            print(f'{func_name} failed!')

    short_output_list = []
    pass_count = 0
    fail_count = 0
    for func_name, output in output_list:
        output_last_line = output.split('\n')[-1]
        if output_last_line.find('ok') != -1:
            short_output_list.append(func_name + ': Passed')
            pass_count += 1
        elif output_last_line.startswith('error'):
            short_output_list.append(func_name + ': Failed')
            fail_count += 1
        else:
            short_output_list.append(func_name + f': Failed ({output_last_line})')
            fail_count += 1
    with open(os.path.join(project_path, 'test_output.txt'), 'w') as f:
            f.write('\n'.join(short_output_list))

    process_summary_str = json.dumps({"通过的测试样例数量": pass_count, "失败的测试样例数量": fail_count}, indent=4, ensure_ascii=False)
    with open(os.path.join(project_path, 'test_summary.json'), 'w', encoding='utf-8') as f:
        f.write(process_summary_str)



if __name__ == '__main__':
    cargo_test(sys.argv[1], sys.argv[2])